<?php


namespace app\common\lib\live;


use app\common\cachemodel\live\LiveSubscribe;
use app\common\lib\Push;
use app\common\lib\Util;
use think\Db;
use think\Log;
use think\queue\Job;

class LiveSubscribeJob
{
    public function subscribeSendTask(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }
        $liveInfo = $jobData['live_info'];
        $liveSubscribeModel = new LiveSubscribe();
        $host = Util::getEcsIp();
        $startTime = date('Y-m-d H:i:s');
        $logInfo = "直播间开播订阅推送 开始:{$startTime} host:{$host} 直播间ID：{$liveInfo['live_id']}";
        $data = $liveSubscribeModel->alias('l')
            ->join('wechat_backup_07_18_14_43_00.app_user_push p', 'l.uid=p.uid')
            ->where(['l.live_id' => $liveInfo['live_id'], 'l.status' => 1])
            ->column('p.device_token,p.regid,p.push_type,l.uid,l.broadcast_id', 'l.id');

        if ($data)
        {   // 发送推送
            $time = time();
            foreach ($data as $id => $datum)
            {
                try
                {
                    // 推送消息
                    $this->push($liveInfo['name'], $datum);
                }
                catch (\Exception $e)
                {
                    Log::write("直播预约通知失败「{$liveInfo['live_id']}」，数据「" . json_encode($datum, JSON_UNESCAPED_UNICODE), 'error', true);
                }

                $liveSubscribeModel->updateData(['id' => $id,'uid'=>$datum['uid'],'borId'=>$datum['broadcast_id']], ['status' => 3, 'update_time' => $time]);

                usleep(10);
            }
        }

        // 删除队列
        $job->delete();

        Log::write($logInfo . " 结束：" . date('Y-m-d H:i:s'), 'log', true);
    }

    private function push($liveName, $msg)
    {
        $extras = [
            'target' => 'local',
            'link' => 'empty',
        ];
        $pushRecordData = [
            'uid' => $msg['uid'],
            'content' => $liveName . '已经开启直播，快来看看吧～',
            'target' => $extras['target'],
            'link' => $extras['link'],
            'title' => '准了',
            'admin_name' => 'api',
            'admin_id' => 0,
            'create_time' => time()
        ];
        $mid = Db::table('wechat_backup_07_18_14_43_00.app_push_record')->insertGetId($pushRecordData);
        $extras['push_id'] = $mid;
        $extras['push_type'] = '个推';
        $extras['push_content'] = $pushRecordData['content'];

        $pushData = [
            'plantform' => $msg['push_type'] == 1 ? 1 : 3, // 1 => all  2 => IOS 3 => android
            'pushType' => $msg['push_type'],
            'regid' => [$msg['regid']],
            'title' => $pushRecordData['title'], // 推送标题
            'content' => $pushRecordData['content'], // 推送内容
            'extras' => $extras, // 扩展字段
            'informType' => 0, //通知栏样式 0默认 1大文本 2收件箱 3大图片
            'bigText' => '', // 大文本内容
            'bigPicPath' => '', // 大图片路径
            'timeToLive' => 86400, // 默认86400
            'device_tokens' => $msg['device_token'] ?? ''
        ];

        $res = (new Push())->pushOne($pushData);

        if (!isset($res['message']))
        {
            $res['message'] = '未知错误';
        }

        return $res;
    }
}
